package cn.edu.ncu.housinghub.service.impl;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.Administrator;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.mapper.admin.AdminMapper;
import cn.edu.ncu.housinghub.service.AdminService;
import cn.edu.ncu.housinghub.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public Result login(String username, String password) {
        System.out.println("🔍 AdminService.login - 接收到参数 - 用户名: " + username + ", 密码: " + password);

        // 先根据用户名查询管理员
        Administrator administrator = adminMapper.selectAdminByUsername(username);
        System.out.println("🔍 数据库查询结果: " + (administrator != null ? administrator.toString() : "null"));

        if (administrator == null) {
            System.out.println("❌ 管理员不存在: " + username);
            throw new BusinessException(ErrorCodeConstant.ADMIN_LOGIN_FAILED);
        }

        // 验证密码（这里可以根据需要添加密码加密验证）
        if (!password.equals(administrator.getAdministratorPassword())) {
            System.out.println("❌ 密码验证失败 - 输入密码: " + password + ", 数据库密码: " + administrator.getAdministratorPassword());
            throw new BusinessException(ErrorCodeConstant.ADMIN_LOGIN_FAILED);
        }

        System.out.println("✅ 管理员登录验证成功: " + username);
        // 先看管理员是否已经登录
        Set<String> keys = redisTemplate.keys(
                SystemConstant.REDIS_TOKEN_PREFIX_ADMIN.getStringValue() +
                        administrator.getAdministratorId().toString() + ":*");
        if (!keys.isEmpty()) {
            // 如果管理员已经登录 则将已登录的管理员删除
            redisTemplate.delete(keys.iterator().next());
            System.out.println("🔄 删除了管理员的旧token，管理员ID: " + administrator.getAdministratorId());
        }

        // 生成新token
        String token = UUID.randomUUID().toString();
        // 将管理员信息存储到Redis中，设置过期时间
        redisTemplate.opsForValue().set(
                SystemConstant.REDIS_TOKEN_PREFIX_ADMIN.getStringValue() +
                        administrator.getAdministratorId().toString() + ":" + token,
                administrator,
                SystemConstant.REDIS_TOKEN_EXPIRE_TIME.getIntegerValue(),
                TimeUnit.MINUTES
        );
        System.out.println("✅ 管理员新token已存储，管理员ID: " + administrator.getAdministratorId() + ", token: " + token.substring(0, 8) + "...");

        ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
        map.put("info", token);
        map.put("loginAdmin", administrator);
        return Result.success(map);
    }

    @Override
    public void logout(String info) {
        if (info == null)
            return;
        String theKey = SystemConstant.REDIS_TOKEN_PREFIX_ADMIN.getStringValue() + "*:" + info;
        Set<String> keys = redisTemplate.keys(theKey);
        if (keys.size() > 0) {
            String key = keys.iterator().next();
            redisTemplate.delete(key);
        }
    }
}
